package com.jp.knowledge.view;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.JpApplicationWebActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.adapter.BigDataItemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.BigDataModel;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.ArrayList;
import java.util.List;

import pl.droidsonroids.gif.GifImageView;

/**
 * Created by 528787067@qq.com on 2017/3/9.
 */

public class BigDataView extends FrameLayout implements ResultSubscriber.OnResultListener, InfoDataDetailBigDataTab.TabItemSelectedListener, OnItemListerner, RecycleVAdapter.OnItemClickListener {
    public BigDataView(Context context) {
        super(context);
        init();
    }

    public BigDataView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BigDataView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private String id;
    private int type;
    public void setData(String id, int type){
        this.id = id;
        this.type = type;
        getData(id, type);
    }

    private InfoDataDetailBigDataTab bigDataTab;
    private ViewPager bigDataPager;
    private GifImageView bigDataLoading;
    private TextView bigDataNoData;
    private TextView bigDataReload;
    private BigDataModel bigDataModel;

    private void init(){
        View contentView = View.inflate(getContext(), R.layout.activity_info_data_detail_bigdata, this);
        bigDataTab = (InfoDataDetailBigDataTab) contentView.findViewById(R.id.bigdata_tab);
        bigDataTab.setOnTabItemClickListener(this);
        bigDataPager = (ViewPager) contentView.findViewById(R.id.big_data_pager);
        bigDataPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
            @Override
            public void onPageScrollStateChanged(int state) {}
            @Override
            public void onPageSelected(int position) {
                bigDataTab.setSelectedItem(position);
            }
        });
        bigDataLoading = (GifImageView) contentView.findViewById(R.id.big_data_loading);
        bigDataNoData = (TextView) contentView.findViewById(R.id.big_data_nodata);
        bigDataReload = (TextView) contentView.findViewById(R.id.big_data_reload);
        bigDataReload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getData(id, type);
            }
        });
    }

    private void getData(String id, int type){
        JsonObject param = new JsonObject();
        param.addProperty("id", id);
        param.addProperty("type", type);
        HttpHelper.getInstance(getContext()).getBigdata(param, 0x01, this);
    }

    @Override
    public void onTabItemSelected(int position) {
        bigDataPager.setCurrentItem(position);
    }

    @Override
    public void onStart(int requestType) {
        bigDataPager.setVisibility(View.GONE);
        bigDataNoData.setVisibility(View.GONE);
        bigDataReload.setVisibility(View.GONE);
        bigDataLoading.setVisibility(View.VISIBLE);
        if(bigDataLoadListener != null)
            bigDataLoadListener.loadStart();
    }
    @Override
    public void onCompleted(int requestType) {
        bigDataLoading.setVisibility(View.GONE);
    }
    @Override
    public void onError(int requestType) {
        if(bigDataLoadListener != null)
            bigDataLoadListener.loadError();
        bigDataPager.setVisibility(View.GONE);
        bigDataNoData.setVisibility(View.GONE);
        bigDataReload.setVisibility(View.VISIBLE);
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
            return;
        }
        bigDataModel = data.getEntity(BigDataModel.class);
        if(bigDataModel == null || bigDataModel.getCount() == 0){
            bigDataReload.setVisibility(View.GONE);
            bigDataPager.setVisibility(View.GONE);
            bigDataNoData.setVisibility(View.VISIBLE);
        } else {
            bigDataTab.initItem(bigDataModel.getCateList());
            bigDataTab.setSelectedItem(0);
            setBigDataPagerAdapter(bigDataModel.getDataList());
            bigDataReload.setVisibility(View.GONE);
            bigDataNoData.setVisibility(View.GONE);
            bigDataPager.setVisibility(View.VISIBLE);
        }
        if(bigDataLoadListener != null)
            bigDataLoadListener.loadFinish(bigDataModel);
    }

    private void setBigDataPagerAdapter(List<List<HeadLineData>> dataList){
        List<View> pagerViews = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){
            for(List<HeadLineData> pagerViewData : dataList){
                View pagerView = View.inflate(getContext(), R.layout.activity_info_data_detail_bigdata_showview, null);
                if(pagerViewData == null || pagerViewData.size() == 0){
                    pagerView.findViewById(R.id.big_data_rv).setVisibility(View.GONE);
                    pagerView.findViewById(R.id.big_data_nocontent).setVisibility(View.VISIBLE);
                } else {
//                    BigDataAdapter bigDataAdapter = new BigDataAdapter(getContext(), pagerViewData);
                    BigDataItemAdapter bigDataItemAdapter = new BigDataItemAdapter(getContext(), pagerViewData);
                    RecyclerView bigDataRv = (RecyclerView) pagerView.findViewById(R.id.big_data_rv);
                    bigDataRv.setHasFixedSize(true);
                    bigDataRv.setLayoutManager(new LinearLayoutManager(getContext()));
//                    bigDataRv.setAdapter(bigDataAdapter);
                    bigDataRv.setAdapter(bigDataItemAdapter);
                    pagerView.findViewById(R.id.big_data_nocontent).setVisibility(View.GONE);
                    bigDataRv.setVisibility(View.VISIBLE);
//                    bigDataAdapter.setOnItemListener(this);
                    bigDataItemAdapter.addItemClickListener(this);
                }
                pagerViews.add(pagerView);
            }
        }
        bigDataPager.setAdapter(new BigDataPagerAdapter(pagerViews));
    }

    @Override
    public void itemSelect(int position) {
        HeadLineData itemData = bigDataModel.getDataList().get(bigDataPager.getCurrentItem()).get(position);
        if(itemData == null)
            return;
        if(itemData.getId() != null && itemData.getId().trim().length() > 0){
            switch (itemData.getType()){
                case 3: // "公司";
                    JpApplicationWebActivity.gotoWebActivity(getContext(),
                            "details/companyDetails?id=" + itemData.getId() + "&type=" + itemData.getType());
                    break;
                case 4: // "人物";
                    JpApplicationWebActivity.gotoWebActivity(getContext(),
                            "details/figureDetails?id=" + itemData.getId() + "&type=" + itemData.getType());
                    break;
                case 8: // "产品";
                    JpApplicationWebActivity.gotoWebActivity(getContext(),
                            "details/productDetails?id=" + itemData.getId() + "&type=" + itemData.getType());
                    break;
                case 11: // "全民推荐";
                    JpApplicationWebActivity.gotoWebActivity(getContext(),
                            "details/recommendDetail?id=" + itemData.getId() + "&type=" + itemData.getType());
                    break;
                default:
                    Intent intent = new Intent(getContext(), InfoDataDetailActivity.class);
                    intent.putExtra("id", itemData.getId());
                    intent.putExtra("type", itemData.getType());
                    intent.putExtra("linkTitle", itemData.getTitle());
                    try {
                        intent.putExtra("linkIcon", itemData.getImglist().get(0).getSrc());
                    }catch (Exception e){}
                    getContext().startActivity(intent);
                    break;
            }
        } else{
            SearchActivity.gotoSearch(getContext(), itemData.getTitle(), itemData.getType());
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        itemSelect(position);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ev.getAction() == MotionEvent.ACTION_DOWN)
            if((ev.getX() < getResources().getDisplayMetrics().widthPixels/10))
                return false;
        return super.dispatchTouchEvent(ev);
    }

    private BigDataLoadListener bigDataLoadListener;
    public void setBigDataLoadListener(BigDataLoadListener listener){
        this.bigDataLoadListener = listener;
    }

    public interface BigDataLoadListener{
        void loadStart();
        void loadFinish(BigDataModel bigDataModel);
        void loadError();
    }

    private class BigDataPagerAdapter extends PagerAdapter{
        private List<View> pagerViews;
        public BigDataPagerAdapter(List<View> pagerViews){
            this.pagerViews = pagerViews;
        }
        @Override
        public int getCount() {
            return pagerViews.size();
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(pagerViews.get(position));
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(pagerViews.get(position));
            return pagerViews.get(position);
        }
        public View getItemView(int position){
            try{
                return pagerViews.get(position);
            } catch (Exception e){
                return null;
            }
        }
    }
}
